package com.xywei.config.security;

import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import com.xywei.domain.Authority;
import com.xywei.domain.Role;
import com.xywei.domain.User;
import com.xywei.service.UserService;

@Component("securityCustomUserDetailsService")
public class SecurityCustomUserDetailsService implements UserDetailsService {

	@Autowired
	private UserService userService;

	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

		User user = userService.findUserAndRoleAndAuthorityByUsername(username);

		if (user == null) {
			throw new UsernameNotFoundException("用户不存在: " + username);
		}

		if (user.getEnable() == 0) {
			throw new DisabledException("用户已经被禁用: " + username);
		}

		String dbUsername = user.getUsername();
		String dbPassword = user.getPassword();
		boolean enabled = true;

		boolean accountNonLocked = true;
		boolean credentialsNonExpired = true;
		boolean accountNonExpired = true;

		Collection<GrantedAuthority> authorities = new HashSet<GrantedAuthority>();
		authorities = obtainAuthorities(user);
		if ("root1".equalsIgnoreCase(username)) {
			SimpleGrantedAuthority authorityRoot = new SimpleGrantedAuthority("root");
			authorities.add(authorityRoot);
		}

		org.springframework.security.core.userdetails.User securityUser = new org.springframework.security.core.userdetails.User(
				dbUsername, dbPassword, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked,
				authorities);

		return securityUser;
	}

	private Collection<GrantedAuthority> obtainAuthorities(User user) {

		Collection<GrantedAuthority> authorities = new HashSet<GrantedAuthority>();
		Iterator<Role> iterator = user.getRoles().iterator();
		if (iterator.hasNext()) {
			System.out.println(iterator.next());
		}
		Set<Role> roles = user.getRoles();
		for (Role role : roles) {
			Set<Authority> authorities2 = role.getAuthorities();
			for (Authority authority : authorities2) {
				String authorityName = authority.getAuthorityName();
				SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(authorityName);
				authorities.add(simpleGrantedAuthority);
			}
		}

		return authorities;
	}

}
